#!/usr/bin/python

import sys
import re
import time
import random
import os

# Read and ignore AGI environment (read until blank line)

env = {}
tests = 0;

while 1:
   line = sys.stdin.readline().strip()

   if line == '':
      break
   key,data = line.split(':')
   if key[:4] <> 'agi_':
      #skip input that doesn't begin with agi_
      sys.stderr.write("Did not work!\n");
      sys.stderr.flush()
      continue
   key = key.strip()
   data = data.strip()
   if key <> '':
      env[key] = data

sys.stderr.write("AGI Environment Dump:\n");
sys.stderr.flush()
for key in env.keys():
   sys.stderr.write(" -- %s = %s\n" % (key, env[key]))
   sys.stderr.flush()

def checkresult (params):
   params = params.rstrip()
   if re.search('^200',params):
      result = re.search('result=(\d+)',params)
      if (not result):
         sys.stderr.write("FAIL ('%s')\n" % params)
         sys.stderr.flush()
         return -1
      else:
         result = result.group(1)
         #debug("Result:%s Params:%s" % (result, params))
         sys.stderr.write("PASS (%s)\n" % result)
         sys.stderr.flush()
         return result
   else:
      sys.stderr.write("FAIL (unexpected result '%s')\n" % params)
      sys.stderr.flush()
      return -2



# Main code starts from here


# Variables

locPrompt = "/home/piyush/Documents/JobPortal/Prompts/" # Create the Prompts folder and add the location of the folder and add the given prompts
locRecord = "/home/piyush/Documents/JobPortal/Record/" # Create the Record folder and add the location of the folder
noDigit = "\""
stopRecording = "1234567890"
recFormat = "wav"
maxTimeout = 10000   # Maximun time for call recording
maxTimeoutQ = 5000   # Maximun time for keypad input
maxDigits = 4
multipleCh = ['49', '50', '51', '52']
recordFeed = "/Response--"
recordAns = "/Ans--"
curTime = time.strftime("%d-%m-%Y---%H:%M:%S")
curDate = time.strftime("%d-%m-%Y")
responseFile = locRecord + curDate + recordFeed + curTime
logFile = locRecord + curDate + '/' + curDate+'.log'

def dirToday():
	if not os.path.exists(locRecord+curDate):	
		os.makedirs(locRecord+curDate)

def playPrompt (prompt, escdigit):
       sys.stderr.write("STREAM FILE %s %s \n" % (prompt, escdigit))
       sys.stderr.flush( )
       sys.stdout.write("STREAM FILE %s %s \n" % (prompt, escdigit))
       sys.stdout.flush( )
       result = sys.stdin.readline( ).strip( )
       return checkresult(result)

def recordFile (recordedFile):
	sys.stderr.write("RECORD FILE %s %s %s %d \n" % (recordedFile, recFormat, stopRecording, maxTimeout))
	sys.stderr.flush( )
	sys.stdout.write("RECORD FILE %s %s %s %d \n" % (recordedFile, recFormat, stopRecording, maxTimeout))
	sys.stdout.flush( )
	result = sys.stdin.readline( ).strip( )
	checkresult(result)
	
def recordFeedback ():
	logF.write('Recording Feedback (Pressed 1)\n')
	playPrompt("digits/1", noDigit)
	playPrompt(locPrompt+"RecordF", noDigit)				
	playPrompt("beep", noDigit)
	recordFile(responseFile)	
	playPrompt(responseFile, noDigit)	
	logF.write('Feedback Recorded at: ' + responseFile + '.wav' + '\n')
	playPrompt(locPrompt+"Thanks", noDigit)
	logF.write("\n\n")				
	logF.close()

def recordResume ():
	logF.write('Recording Resume (Pressed 2)\n')
	playPrompt("digits/2", noDigit)
	playPrompt(locPrompt+"RecordR", noDigit)				
	playPrompt("beep", noDigit)
	startQ1()
	startQ2()
	startQ3()
	playPrompt(locPrompt+"Thanks", noDigit)				
	logF.write("\n\n")				
	logF.close()

def wait ():
	sys.stderr.write("WAIT FOR DIGIT 5000 \n")
	sys.stderr.flush( )
	sys.stdout.write("WAIT FOR DIGIT 5000 \n")
	sys.stdout.flush( )
	result = sys.stdin.readline( ).strip( )
	result = checkresult(result)	
	return result

def enterNo(prompt):
	sys.stderr.write("GET DATA %s %d %d\n" % (prompt, maxTimeoutQ, maxDigits))
	sys.stderr.flush( )
        sys.stdout.write("GET DATA %s %d %d\n" % (prompt, maxTimeoutQ, maxDigits))
        sys.stdout.flush( )
        result = sys.stdin.readline( ).strip( )
        result = checkresult(result)
	return result

def startQ1 ():
	for var in range (1, 6):
		playPrompt("digits/"+str(var), noDigit)
		playPrompt("letters/q", noDigit)
		recordFile(locRecord + curDate + recordAns + str(var) + "--" + curTime)
		logF.write('\nAnswer'+str(var)+': ')		
		logF.write(locRecord + curDate + recordAns + str(var) + "--" + curTime + '.wav')

def startQ2 ():
	for var in range (6, 11):
		playPrompt("digits/"+str(var), noDigit)
		playPrompt("letters/q", noDigit)
		while 1:		
			result = wait()	
			if result in multipleCh:
				logF.write('\nAnswer'+str(var)+': ')				
				logF.write(result)	
				break
			else:
				playPrompt("digits/"+str(var), noDigit)
				playPrompt("letters/q", noDigit)

def startQ3 ():
	for var in range (11, 16):
		result = enterNo("digits/"+str(var))
		while 1:
			if result == -1:
				result = enterNo("digits/"+str(var))					
			elif len(result) < 4:
				result = enterNo("digits/"+str(var))
			else:	
				logF.write('\nAnswer'+str(var)+': ')
				logF.write(result)				
				sys.stderr.write("Entered Digits Are %s\n" % result)
	 			sys.stderr.flush( )				
				break
	
result = playPrompt(locPrompt+"Welcome", "12")
dirToday()
logF = open(logFile, 'a')
logF.write('\n- - - NEW CALL BEGINS - - -\n')

if result == '49':
	recordFeedback()
elif result == '50':
	recordResume()
else:	
	while 1:
		playPrompt("beep", "\"")
		result = wait()
		if result == '49':
			recordFeedback()
			break
		elif result == '50':
			recordResume()
			break
		else:
			result = playPrompt(locPrompt+"Welcome", "12")

